<template>
  <div id="supplementWrapper">
    <el-row>
        <el-col :xs="24" :sm="24" :lg="24" class="primary">持续改进积分</el-col>
    </el-row>
    <el-row>
        <el-col :xs="24" :sm="24" :lg="24" class="border"></el-col>
    </el-row>
    <el-row class="bgColor">
      <el-col :xs="24" :sm="24" :lg="24" class="choose-flex">
        <div class="group-radio">
          <el-checkbox v-model="selectAllRadio">集团</el-checkbox>
        </div>
        
        <div class="group-radio">
          <div :label="1" style="margin-right: 30px;" class="flex-radio radioEl">
            事业群
            <el-select multiple collapse-tags @change="groupChange" clearable style="margin-left: 6px;" v-model="selectedgroupId" filterable placeholder="请选择事业群">
              <el-option
                v-for="item in group_selector"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="time-box">
          <label class="col-form-label" style="font-size:15px;font-weight: 500;">时间段：</label>
          <!-- :value-format="dateType =='daterange' ? 'yyyy-MM-dd' : 'yyyy-MM'" -->
          <el-date-picker
              v-model="dateTimes"
              placeholder="选择月份"
              :type="dateType"
              align="right"
              size="small"
              value-format="yyyy-MM"
              @change="changeTime"
              :default-time="dateTimes"
              class="mr-4">
          </el-date-picker>
        </div>
        <el-button class="loader" type="primary" @click="getExcelFile" :loading="loadingbut">{{loadingbuttext}}</el-button>    
      </el-col>
    </el-row>
      <el-card>
          <div id="newimprove" class="supplement-table bgColor marT" style="position: relative;"> 
            <el-row>   
              <el-col :xs="24" :sm="24" :lg="24">
                <el-form :model="ruleForm" :rules="ruleForm.rules" ref="ruleForm">
                  <el-table
                    :header-cell-style="{background:'#eef1f6'}"
                    :data="ruleForm.continuousScoreList"  
                    v-loading="loading"    
                    element-loading-text="加载中"
                    element-loading-spinner="el-icon-loading"                  
                    style="width: 100%">
                        <el-table-column
                            label="事业群"
                            align="center"> 
                            <template slot-scope="scope">
                              <div>{{ scope.row.group_name }}</div>
                            </template>    
                        </el-table-column>
                        <el-table-column
                            label="一级部门"
                            width="180"
                            align="center"> 
                            <template slot-scope="scope">
                              <div :key="'dept-'+deptIndex" v-for="(deptItem, deptIndex) in scope.row.dept">
                                <div :class="{'borders': deptIndex !== scope.row.dept.length - 1}" style="height: 40px;line-height: 40px;">{{ deptItem }}</div>
                              </div> 
                            </template>    
                        </el-table-column>
                        <el-table-column
                            label="持续改进接口人"
                            align="center"> 
                            <template slot-scope="scope">
                              <div :key="'impl-'+implIndex" v-for="(implItem, implIndex) in scope.row.impl_user">
                                <div :class="{'borders': implIndex !== scope.row.impl_user.length - 1}" style="height: 40px;line-height: 40px;">{{ implItem }}</div>
                              </div> 
                            </template>    
                        </el-table-column>

                        <el-table-column
                            label="QA"
                            align="center"> 
                            <template slot-scope="scope">
                              <div :key="'qa-'+qaIndex" v-for="(qaItem, qaIndex) in scope.row.qa">
                                <div :class="{'borders': qaIndex !== scope.row.qa.length - 1}" style="height: 40px;line-height: 40px;">{{ qaItem }}</div>
                              </div> 
                            </template>   
                        </el-table-column> 

                        <el-table-column
                            v-if="isShowData"
                            width="120"
                            label="KPI人数"
                            align="center">  
                            <template slot-scope="scope">
                              <div :key="'person-'+kpiPersonIndex" v-for="(kpiPersonItem, kpiPersonIndex) in scope.row.kpi_person_num">
                                <div :class="{'borders': kpiPersonIndex !== scope.row.kpi_person_num.length - 1}" style="height: 40px;line-height: 40px;">
                                  <el-input
                                    v-if="scope.row.status"
                                    placeholder="请输入正整数"
                                    v-model="scope.row.kpi_person_num[kpiPersonIndex]"
                                    onkeyup="this.value = this.value.replace(/[^\d]|^0/g,'');"
                                    autocomplete="off"
                                    >
                                  </el-input>
                                  <!-- <span v-else>{{ kpiPersonItem }}</span> -->
                                </div>
                              </div> 
                            </template>
                        </el-table-column>

                        <el-table-column
                            v-if="isShowData"
                            width="150"
                            label="KPI权重"
                            align="center">  
                            <template slot-scope="scope">
                              <div :key="'weight-'+kpiWeightIndex" v-for="(kpiWeightItem, kpiWeightIndex) in scope.row.kpi_weight">
                                <div :class="{'borders': kpiWeightIndex !== scope.row.kpi_weight.length - 1}" style="height: 40px;line-height: 40px;">
                                  <el-input
                                    v-if="scope.row.status"
                                    placeholder="请输入<=1的正数"
                                    onkeyup="this.value = this.value.replace(/^[1-9]\.|^\.|[\.][1-9]*[\.]|^0[0-9]|^[2-9]|^1[0-9]|[^(\d|\.)]/g,'');"
                                    v-model="scope.row.kpi_weight[kpiWeightIndex]" 
                                    autocomplete="off"
                                    >
                                  </el-input>
                                  <!-- <span v-else>{{ kpiWeightItem }}</span> -->
                                </div>
                              </div> 
                            </template>    
                        </el-table-column> 

                        <el-table-column
                            label="KPI"
                            align="center">  
                            <template slot-scope="scope">
                              <div :key="'kpi-'+kpiIndex" v-for="(kpiItem, kpiIndex) in scope.row.kpi">
                                <div :class="{'borders': kpiIndex !== scope.row.kpi.length - 1}" style="height: 40px;line-height: 40px;">{{ kpiItem }}</div>
                              </div> 
                            </template>    
                        </el-table-column> 

                        <el-table-column
                            label="积分"
                            align="center">   
                            <el-table-column
                              label="跬步行动"
                              align="center"> 
                              <template slot-scope="scope">
                                <div :key="'qcc-'+qccIndex" v-for="(qccItem, qccIndex) in scope.row.qcc">
                                  <div :class="{'borders': qccIndex !== scope.row.qcc.length - 1}" style="height: 40px;line-height: 40px;">{{ qccItem }}</div>
                                </div> 
                              </template>  
                              </el-table-column> 
                              <el-table-column
                              label="项目知识"
                              align="center">
                                <template slot-scope="scope">
                                  <div :key="'knowledge-'+knowledgeIndex" v-for="(knowledgeItem, knowledgeIndex) in scope.row.knowledge">
                                    <div :class="{'borders': knowledgeIndex !== scope.row.knowledge.length - 1}" style="height: 40px;line-height: 40px;">{{ knowledgeItem }}</div>
                                  </div> 
                                </template>    
                              </el-table-column>  
                              <el-table-column
                              label="改进建议"
                              align="center">
                                <template slot-scope="scope">
                                  <div :key="'improve-'+improveIndex" v-for="(improveItem, improveIndex) in scope.row.improve">
                                    <div :class="{'borders': improveIndex !== scope.row.improve.length - 1}" style="height: 40px;line-height: 40px;">{{ improveItem }}</div>
                                  </div> 
                                </template>
                              </el-table-column> 
                              <el-table-column
                              label="当前共计"
                              align="center">
                                <template slot-scope="scope">
                                  <div :key="'total-'+totalIndex" v-for="(totalItem, totalIndex) in scope.row.current_total">
                                    <div :class="{'borders': totalIndex !== scope.row.current_total.length - 1}" style="height: 40px;line-height: 40px;">{{ totalItem }}</div>
                                  </div> 
                                </template>
                              </el-table-column>
                              <el-table-column
                                v-if="isShowData"
                                label="BG共计"
                                align="center"
                                prop="bg_total">
                            </el-table-column>
                        </el-table-column>

                        <el-table-column
                            label=""
                            align="center">   
                              <el-table-column
                              v-if="isShowData"
                              width="120"
                              label="活动积分"
                              align="center">
                                <template slot-scope="scope">
                                  <el-input
                                    v-if="scope.row.status"
                                    placeholder="请输入正整数"
                                    onkeyup="this.value = this.value.replace(/[^\d]|^0/g,'');"
                                    v-model="scope.row.activity_score" 
                                    autocomplete="off"
                                    >
                                  </el-input>
                                  <!-- <span v-else>{{ scope.row.activity_score }}</span> -->
                                </template>
                              </el-table-column>
                              <el-table-column
                                label="BG共计"
                                align="center"
                                prop="bg_total_show">   
                            </el-table-column>
                        </el-table-column>

                        <el-table-column
                            label="KPI达成比例"
                            align="center"
                            prop="kpi_reach_ratio">   
                        </el-table-column>

                        <el-table-column
                            label="人均"
                            align="center"
                            prop="kpi_avg">   
                        </el-table-column>

                        <el-table-column
                            label="KPI达成排名"
                            align="center"
                            prop="kpi_rank">   
                        </el-table-column>

                        <el-table-column
                            label="人均排名"
                            align="center"
                            prop="kpi_avg_rank">   
                        </el-table-column>

                        <el-table-column
                            label="综合排名"
                            align="center"
                            prop="total_rank">   
                        </el-table-column>

                        <el-table-column fixed="right" align="center" label="操作" v-if="edit">
                          <template slot-scope="scope">
                            <div style="margin-bottom: 5px;">
                              <el-button @click="groupEdit(scope.row, scope.$index)" size="mini" round type="success">修改</el-button>
                            </div>

                            <div v-if="scope.row.status" style="margin-bottom: 5px;">
                              <el-button @click="groupCancel(scope.row, scope.$index)" size="mini" round type="warning">取消</el-button>
                            </div>

                            <div>
                              <el-button @click="groupSave(scope.row, scope.$index)" size="mini" round type="primary" :disabled="error || !scope.row.status">保存</el-button>
                            </div>
                          </template> 
                        </el-table-column>
                  </el-table>
                </el-form>
              </el-col>
            </el-row>
          </div>
        </el-card>
  </div>
</template>

<script>
import DataChoose from '@/views/data/dataChoose'
import { getHeader } from '@/app.config'
import { getHeader1 } from '@/app.config'
import { mapState } from 'vuex'
import { Loading } from 'element-ui'

export default {
  components: {
    DataChoose
  },
  computed: {
    ...mapState({
        dataChoose: state => state.dataChoose,
        entry: state => state.entry,
        entryList: state => state.entryItem
    }),
    edit() {
      let status = false
      status = this.entryList.cont_score_perm === 1 ? true : false
      return status
    },
  },
  created() {   
    if(this.entry == 0) {      
      this.$router.push({
        path: '/'
      })
    }
  },
  data() {
    var validatePercent = (rule, value, callback) => {
      if (!(/^(\d{1,2}(\.\d{1,5})?|100)$/).test(value)) {
        this.error = true
        callback(new Error('请输入正确的百分数'));
      } else {
        this.error = false
        callback()
      }
    };
    var validateNum = (rule, value, callback) => {
      if(!(/^([1-9]\d*|[0]{1,1})$/).test(value)) {
        this.error = true
        callback(new Error('请输入正整数!'));
      } else {
        this.error = false
        callback()
      }
    };
    var validateStr = (rule, value, callback) => {
      if(!(/(^$)|^([1-9]\d*|[0]{1,1})$/).test(value)) {
        this.error = true
        callback(new Error('请输入正整数!'));
      } else {
        this.error = false
        callback()
      }
    };
    var validatePercentStr = (rule, value, callback) => {
      if (!(/(^$)|^(\d{1,2}(\.\d{1,5})?|100)$/).test(value)) {
        this.error = true
        callback(new Error('请输入正确的百分数'));
      } else {
        this.error = false
        callback()
      }
    };
    return { 
      // 导出数据
      // downloadInfo: {
      //   group: '', 
      //   projectType: '',
      //   projectType2: ''
      // },
      
      loadingbut: false,
      loadingbuttext:'导出',
      loading: false,
      selectAllRadio: false,
      isShowData: false,
      error: false,
      newSuccess: false,
      selectedgroup: [],
      selectedgroupId: [],
      group_selector: [],
      dateTimes: '',
      dateType: 'month',
      ruleForm: {
        continuousScoreList: [],
        rules: {
          pass: [
            { validator: validatePercent, trigger: 'change' }
          ],
          number: [
            { validator: validateNum, trigger: 'change' }
          ],
          str: [
            { validator: validateStr, trigger: 'change' }
          ],
          percentStr: [
            { validator: validatePercentStr, trigger: 'change' }
          ]
        }
      } 
    }
  },
  watch: {
      selectAllRadio(newVal,oldVal) {
        if(oldVal === false && newVal === true) {
          this. loading = true
          this.selectedgroupId = []
          this.group_selector.forEach(val => {
              this.selectedgroupId.push(val.value)
          })
          console.log()
          this.groupInitData()
          // this. loading = false
        } 
      }
  },
  mounted() {
    this.defaultTime()
    this.init()
  },
  methods: {
    // 导出数据
    getExcelFile() {
        this. loadingbut = true
        this. loadingbuttext = "导出中..."
        this.$axios.get(`${process.env.VUE_APP_KANBAN_HOST}/api/indicator/kanban_data?group=${this.selectedgroupId.toString()}&date=${this.dateTimes}&download=true`,{headers: getHeader(),responseType: 'blob',})
        .then(res => {
          const { data, status } = res
          if(status === 200) {
            
            let blob = new Blob([data], {type: 'application/vnd.ms-excel'})
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = URL.createObjectURL(blob)
            link.setAttribute('download', '持续改进看板报表.xlsx')
            document.body.appendChild(link)
            link.click()
            URL.revokeObjectURL(link.href)
            document.body.removeChild(link)
            this. loadingbut = false
            this. loadingbuttext = "导出"
             
          }else {
            this.$message.error('下载出错了!'); 
          }
        }).catch(err => {
          const { data } = err
          
          if(data) {
            let blob = new Blob([data], {type: 'application/vnd.ms-excel'})
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = URL.createObjectURL(blob)
            link.setAttribute('download', '持续改进看板报表.xlsx')
            document.body.appendChild(link)
            link.click()
            URL.revokeObjectURL(link.href)
            document.body.removeChild(link)
          } else {
            this.$message.error('下载出错了!'); 
          }          
        })
      },
    number(){　　
　　　 this.famount=this.famount.replace(/[^\.\d]/g,'');
      this.famount=this.famount.replace('.','');
　　},
    formatter(num) {
      num ? `${(num * 100).toFixed(2)}%` : '0.00%'
      return num
    },
    tableRowClassName({row, rowIndex}) {
      if(row.selectStatus == '否') {
        return 'disabled-row';
      }
    },
    isDisabled(status, disabled) {
      let statusBool, isDisabledStatus
      status == "是" ? statusBool = false : statusBool = true

      if(disabled == true) {
        return isDisabledStatus = true
      } else {
        if(!statusBool) {
          isDisabledStatus = false
        } else {
          isDisabledStatus = true
        }
        return isDisabledStatus
      }
    },
    defaultTime() {
        let end = new Date()
        let start = new Date()

        let ye = start.getFullYear()
        let me = start.getMonth() + 1

        if(me.toString().length == 1) {
          me = "0" + me
        }
        let ending = `${ye}-${me}`
        this.dateTimes = ending
    },
    newReload() {
      this.groupInitData()
    },
    groupChange(value) {
      if(value.length < this.group_selector.length) {
        this.selectAllRadio = false
      }
      this.selectedgroupId = value
      
      this.groupInitData()
    },
    changeTime(val) {
      console.log(val)
      this.groupInitData()
    },
    init() {
      this.$axios.get(`${process.env.VUE_APP_KANBAN_HOST}/api/account/personal_group_dept`, {headers: getHeader()})
      .then(res => {
        if(res.data.code === 200) {
          this.isShowData = false
          this.group_selector = res.data.group_info
          this.selectedgroup.push(this.group_selector[0].label)
          this.selectedgroupId.push(this.group_selector[0].value)
          this.groupInitData()
        } else if (res.data.code == 401) {
          removeToken()
          removeName()
          this.$message.error('登陆超时或该账号已被登出，请您重新登录');
          this.$router.push({
              path: '/#/login'
          })
        }
      }).catch(error => {
        console.log(error)
      })
    },
    groupCancel(row, index) {
      row.status = false
      this.isShowData = false
      this.$set(this.ruleForm.continuousScoreList, index, row)
      this.newReload()
    },
    groupEdit(row, index) {
      row.status = true
      this.isShowData = true
      this.$set(this.ruleForm.continuousScoreList, index, row)
    },
    groupInitData() {
      // 表格默认数据
      this.$axios.get(`${process.env.VUE_APP_KANBAN_HOST}/api/indicator/kanban_data?group=${this.selectedgroupId.toString()}&date=${this.dateTimes}`, {headers: getHeader()})
      .then(res => {
        if(res.status === 200) {
          if(res.data.code === 200) {
            this. loading = false
            this.ruleForm.continuousScoreList = res.data.data
            this.ruleForm.continuousScoreList.forEach(val => {
              val.status = false
              if(!val.selectStatus) {
                val.selectStatus = ''
              }
            })            
          }
        }
      })
    },
    groupSave(row, index) {
      let obj = {}
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          let kpi_person_num = row.kpi_person_num.map((item) => {
            return parseInt(item)
          })
          let kpi_weight = row.kpi_weight.map((item) => {
            return parseFloat(item)
          })
            obj = {
              dept: row.dept,              
              kpi_person_num: kpi_person_num,
              kpi_weight: kpi_weight,
              activity_score: row.activity_score ? parseInt(row.activity_score) : 0,
              date: this.dateTimes
            }

            this.newSubmit(obj,row.group_id) 

          row.status = false
          this.isShowData = false
          this.$set(this.ruleForm.continuousScoreList, index, row)
          // setTimeout(() => {
          //   this.newReload()
          // }, 1000)        
        } else {
          this.$message({
            showClose: true,
            message: '提交错误!',
            type: 'error'
          })
          return false
        }
      })
    },

    newSubmit(data,group) {
      this.$axios.post(`${process.env.VUE_APP_KANBAN_HOST}/api/indicator/kanban_data?group=${group}`, data, {headers: getHeader()})
      .then(res => {
        if(res.status === 200) {
          if(res.data.code === 200) {
            this.newSuccess = true
            this.$message({
              showClose: true,
              message: '录入成功!',
              type: 'success'
            })
            if(this.newSuccess) {
              this.newReload()
            }
          } else {
            this.$message({
              showClose: true,
              message: res.data.msg,
              type: 'error'
            })
          }
        }
      }).finally(() => {
        this.newSuccess = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  @import '../../assets/common/common.scss';
  /deep/ .el-table th.gutter{
    display: table-cell!important;
  }
  /deep/ .disabled-row{
    background: #F5F7FA;
  }
  .loader {
    margin-top: auto;
    margin-right: 0px;
    margin-bottom: auto;
    margin-left: 50%;
  }
  #supplementWrapper{
    padding: 32px;
    background-color: rgb(240, 242, 245);
    position: relative;
  }
  #supplementWrapper >>> .el-table .cell{
    padding: 0;
  }
  #supplementWrapper >>> .el-table--medium td{
    padding: 0;
  }
  #point >>>  .el-table--medium td, #improve >>>  .el-table--medium td, #newimprove >>>  .el-table--medium td{
    padding: 10px 0;
  }
  .red{
    color: #F56C6C;
  }
  .log{
    position: relative;
    top: -39px;
    left: -20px;   
    float: right;
  }
  .border{
      box-sizing: content-box;
      height: 0;
      overflow: visible;
      margin-top: 1rem;
      margin-bottom: 1rem;
      border: 0;
      border-top: 1px solid rgba(0,0,0,.1);
  }
  .borders{
    border-bottom: 1px solid #dfe6ec;
    white-space:nowrap;
  }
  
  .primary{
      color: #409EFF;
      font-size: 30px;
      margin-top: 20px;
      margin-bottom: 10px;
      font-weight: 400;
  }
  .bgColor{
      background: #fff;
  }
  .pad{
      padding: 0 20px;
      padding-top: 20px;
  }
  .marT{
      margin-top: 20px;
  }
  .bgColor{
    background: #ffffff;
    padding: 20px;
    .choose-flex{
      display: flex;
      .group-radio{
        // flex: 0 0 60%;
        margin: auto 0;
        display: flex;
        flex-wrap: wrap;
        margin-right: 15px;
        .flex-radio{
          flex: 1;
          margin: auto 0;
        }
      }
      .time-box{
        margin: auto 0;
      }
      .report_box {
        flex: 1;
        margin-left: 45px;
      }
    }
  }
</style>
